import React,{Component} from 'react';


import {observer,inject} from "mobx-react";
import {computed,toJS} from "mobx";


import {View} from "../component/index";
import {
  UploadOutlined,
  PlusOutlined,
  DeleteOutlined,
  AccountBookOutlined,
  SaveOutlined,
  PictureOutlined,
  LoadingOutlined,
  CloseOutlined
} from '@ant-design/icons';
import {
  Select,
  Input,
  Button,
  Modal,
  Tree,
  Upload,
  Tabs,
  Switch,
  Cascader,
  Spin,
  Radio,
  InputNumber,
  Slider,
  Image
} from "antd";
const { Option } = Select;
const {TextArea } = Input;
const { TabPane } = Tabs;

const sty={
  view:{
    padding:5,
    flexDirection:"row",
    jusitifyContent:"center",
    alignItems:"center",
    maxWidth:600,
    height:50,
  }
}

// 商品编辑
@inject(["store"])
@observer
class ProductEdit extends Component{
  constructor(props){
    super(props);
    this.store = props.store;
    this.product = props.store.storeProductEdit;
    this.product.set("id",this.props.match.params.id?this.props.match.params.id:0)
  }
  
  componentDidMount(){
    this.store.navigation({page:"ProductEdit"});
    this.product.init();
  }


  // 高度
  @computed get height(){return this.store.height;}
  @computed get sys(){return this.store.website.sys;}
  @computed get user(){return this.store.user;}
  // 地区数据
  @computed get addr(){return this.store.addr;}

  // loading
  @computed get loading(){return this.product.loading;}
  @computed get loadingUploadImage(){return this.product.loadingUploadImage;}
  // 商品数据
  @computed get data(){return toJS(this.product.data);}
  // 分类数据
  @computed get options(){return this.product.options;}
  // 分类名称
  @computed get ttit(){return this.product.ttit;}
  // 地区名称
  @computed get atit(){return this.product.atit;}


  // 不同规格价格参数
  @computed get params(){return toJS(this.product.data.params.params);}
  // 不同参数组合及价格
  @computed get prices(){return toJS(this.product.data.params.prices);}
 

  
  // 组合参数价格
  _priceArgs(){
    const args = this.params.map(item=>item.args);
    console.log(args);
    if(!args[0]){return [];}
    const results = [];
    const result = [];
    const _doExchange=(arr, index)=>{
      for (let i = 0; i<arr[index].length; i++) {
        result[index] = arr[index][i];
        if (index != arr.length - 1) {
            _doExchange(arr, index + 1);
        } else {
            // results.push(result.join(","));
            const r=result.map(item=>item);
            // r=[...r,"",""];
            results.push(r);
        }
      }
    };
    _doExchange(args, 0);
    return results;
  }
  
 
  
  // 图片限制
  _beforeUpload(file) {
    const cont = this.sys.filetype?this.sys.filetype.replace(/,/g,"|"):"jpg|jpeg|png|gif";
    const reg = new RegExp("".concat(cont,"$"));
    const isJpgOrPng = reg.test(file.type);
    if (!isJpgOrPng) {
      this.store.antd.message.error(`请上传这些格式的图片(${this.sys.filetype})`);
    }
    const isLt2M = file.size / 1024 / 1024 < (this.sys.filesize?Number(this.sys.filesize):1);
    if (!isLt2M) {
      this.store.antd.message.error(`图片大小不能超过${this.sys.filesize}MB`);
    }
    return isJpgOrPng && isLt2M;
  }

  render(){
    if(!this.data.product){
      return <View style={{flex:1,justifyContent:"center",alignItems:"center"}}>
        <Spin />
      </View>;
    }
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    // const priceArgs=this._priceArgs();

    const tabSty={
      overflowY:"auto",
      // tab内的高度
      height:this.height-150,
    };
    const options=["台","件","套","瓶","双","只","付","个","尊","把","罐","包","盒","辆","升","方","块"
    ].map(item=><Option key={item} value={item}>{item}</Option>);
 
    return (
      <View style={{flexDirection:"column",height:this.height,width:"100%",paddingLeft:10,paddingRight:10}}>
        <Tabs
          defaultActiveKey="product"
          tabBarExtraContent={{
            right:<Button type="primary" danger onClick={()=>this.product.submit()}><SaveOutlined />保存</Button>
          }}
          >
          <TabPane style={tabSty} tab="基础信息" key="product">
            <View style={{...sty.view,width:100,height:100}}>
              <span>封面图片</span>
              {
                !this.data.product.image?
                null:
                <Image
                  style={{marginRight:5,width:100,height:100}}
                  src={this.data.product.image} alt="商品图片"
                />
              }
              <View style={{marginLeft:15}}>
                <Upload
                  withCredentials
                  showUploadList={false}
                  name="image"
                  action={this.store.url.concat("?act=admin-upload&tp=image")}
                  onChange={info=>this.product.uploadChange(info,"image")}
                  beforeUpload={file=>this._beforeUpload(file)}
                  >
                  <View style={{cursor:"pointer",textAlign:"center",border:"1px dashed #ccc",width:98,height:98,flexDirection:"column",alignItems:"center",justifyContent:"center"}}>
                    {this.loadingUploadImage ? <LoadingOutlined /> : <PlusOutlined />}
                    <div style={{ marginTop: 8 }}>Upload</div>
                  </View>
                </Upload>
              </View>
            </View>
            <View style={sty.view}>
              <Input
                size="large"
                addonBefore="商铺编号"
                disabled={this.loading}
                placeholder="商铺编号"
                value={this.data.product.sid}
                onChange={e=>this.product.set("data-product-sid",e.target.value.match(/^\d{0,11}/g)[0])}
              />
            </View>
            <View style={sty.view}>
              <Input
                size="large"
                addonBefore="商品名称"
                disabled={this.loading}
                placeholder="商品名称(20个字符以内)"
                value={this.data.product.tit}
                onChange={e=>this.product.set("data-product-tit",e.target.value.match(/^\S{0,20}/g)[0])}
              />
            </View>
            <View style={sty.view}>
              <Cascader
                options={this.options}
                loadData={this.product.onLoadOption}
                onChange={(value,selectedOptions)=>{
                  const len = value.length-1;
                  this.product.set("ttit",selectedOptions[len].label);
                  this.product.set("data-product-tid",value[len]);
                }}
                changeOnSelect
                >
                <Input addonBefore="商品分类" readOnly value={this.ttit} />
              </Cascader>
            </View>
            <View style={sty.view}>
              <Input
                size="large"
                addonBefore="商品原价"
                addonAfter="￥"
                // suffix={<AccountBookOutlined style={{color:"red"}} />}
                disabled={this.loading}
                placeholder="商品原价"
                value={this.data.product.priceall}
                onChange={e=>{
                  const v = e.target.value;
                  let value= /^\d{1,9}(\.\d{0,2})?/.test(v)?v.match(/^\d{1,9}(\.\d{0,2})?/g)[0]:"";
                  if(value>10000000){value=9999999.99}
                  this.product.set(
                    "data-product-priceall",
                    value
                  )
                }}
              />
            </View>
            <View style={sty.view}>
              <Input
                size="large"
                addonBefore="最高押金"
                addonAfter="￥"
                disabled={this.loading}
                placeholder="最高押金"
                value={this.data.product.deposit}
                onChange={e=>{
                  const v = e.target.value;
                  let value= /^\d{1,9}(\.\d{0,2})?/.test(v)?v.match(/^\d{1,9}(\.\d{0,2})?/g)[0]:"";
                  if(value>10000000){value=9999999.99}
                  this.product.set(
                    "data-product-deposit",
                    value
                  )
                }}
              />
            </View>
            <View style={sty.view}>
              <Input
                size="large"
                addonBefore="租机价格"
                addonAfter="￥/天"
                // suffix={<AccountBookOutlined style={{color:"red"}} />}
                disabled={this.loading}
                placeholder="租机价格"
                value={this.data.product.price}
                onChange={e=>{
                  const v = e.target.value;
                  let value= /^\d{1,9}(\.\d{0,2})?/.test(v)?v.match(/^\d{1,9}(\.\d{0,2})?/g)[0]:"";
                  if(value>10000000){value=9999999.99}
                  this.product.set(
                    "data-product-price",
                    value
                  )
                }}
              />
            </View>
            <View style={sty.view}>
              <Input
                size="large"
                addonBefore="起租时间"
                addonAfter="天"
                disabled={this.loading}
                placeholder="最低起租时间"
                value={this.data.product.pricetm}
                onChange={e=>{
                  const v = e.target.value;
                  if(!/^\d+$/.test(v) && v!==""){return}
                  this.product.set(
                    "data-product-pricetm",
                    v
                  )
                }}
              />
            </View>
            <View style={sty.view}>
              <Input
                size="large"
                addonBefore="商品单位"
                disabled={this.loading}
                placeholder="商品单位"
                value={this.data.product.unit||""}
                addonAfter={<Select value={this.data.product.unit||""} onSelect={v=>this.product.set("data-product-unit",v)} defaultValue="件">{options}</Select>}
                onChange={e=>this.product.set("data-product-unit",e.target.value.match(/^\S{0,10}/g)[0])}
              />
            </View>
            <View style={sty.view}>
              <Input
                size="large"
                value={this.data.product.sales}
                addonBefore="商品销量"
                disabled={this.loading} 
                placeholder="商品销量"
                onChange={e=>this.product.set(
                  "data-product-sales",
                  /^\d{0,8}/.test(e.target.value)?e.target.value.match(/^\d{0,8}/g)[0]:""
                )}
              />
            </View>
            <View style={sty.view}>
              <Input
                size="large"
                value={this.data.product.inventory}
                addonBefore="库存"
                disabled={this.loading}
                placeholder="商品库存"
                onChange={e=>this.product.set(
                  "data-product-inventory",
                  /^\d*$/.test(e.target.value)?(e.target.value.match(/^\d*/g)[0]>99999?99999:e.target.value.match(/^\d*/g)[0]):""
                )}
              />
            </View>
            <View style={sty.view}>
              <Radio.Group
                buttonStyle="solid"
                disabled={this.loading} 
                value={this.data.product.buyout}
                onChange={e=>this.product.set("data-product-buyout",e.target.value)}
                >
                <Radio.Button value={0}>不可买断</Radio.Button>
                <Radio.Button value={1}>可买断</Radio.Button>
              </Radio.Group>
            </View>
            <View style={sty.view}>
              <Radio.Group
                buttonStyle="solid"
                disabled={this.loading} 
                value={this.data.product.shopsrecommend}
                onChange={e=>this.product.set("data-product-shopsrecommend",e.target.value)}
                >
                <Radio.Button value={0}>取消推荐</Radio.Button>
                <Radio.Button value={1}>店铺推荐</Radio.Button>
              </Radio.Group>
            </View>
            <View style={sty.view}>
              <Radio.Group
                buttonStyle="solid"
                disabled={this.loading} 
                value={this.data.product.shutdown}
                onChange={e=>this.product.set("data-product-shutdown",e.target.value)}
                >
                <Radio.Button value={0}>上架</Radio.Button>
                <Radio.Button value={1}>下架</Radio.Button>
              </Radio.Group>
            </View>
          </TabPane>
          <TabPane  style={tabSty} tab="上传展示图片" key="image">
            <div style={{padding:10,fontSize:14}}>
              不超过8张图片，图片大小不超过
              {this.sys&&this.sys.filesize?(this.sys.filesize<1?this.sys.filesize*1000:this.sys.filesize):1}{this.sys&&this.sys.filesize<1?"KB":"MB"}，
              图片格式{this.sys && this.sys.filetype?this.sys.filetype:"jpg,jpeg,png"}
            </div>
            <Upload
              multiple
              action={this.store.url.concat("?act=admin-upload&tp=image")}
              listType="picture-card"
              name="image"
              fileList={this.data.image}
              onPreview={this.handlePreview}
              onChange={({ file,fileList }) => {
                if(file.type && !this._beforeUpload(file)){return;}
                const images=fileList.map((item,index)=>{
                  let data=item;
                  if(item.response){
                    const sfx=item.response.data.split(',');
                    data={
                      uid: `-${index}`,
                      name: "image.".concat(sfx[sfx.length-1]),
                      status: 'done',
                      url:item.response.data
                    }
                  }
                  return data;
                });
                this.product.set("data-image",images);
              }}
              beforeUpload={file=>this._beforeUpload(file)}
              >
              {this.data.image.length >= 8 ? null : uploadButton}
            </Upload>
          </TabPane>
          <TabPane  style={tabSty} tab="详情内容" key="detail">
            <div style={{padding:10,fontSize:14}}>
              不超过8张图片，图片大小不超过
              {this.sys&&this.sys.filesize?(this.sys.filesize<1?this.sys.filesize*1000:this.sys.filesize):1}{this.sys&&this.sys.filesize<1?"KB":"MB"}，
              图片格式{this.sys && this.sys.filetype?this.sys.filetype:"jpg,jpeg,png"}
            </div>
            <Upload
              multiple
              action={this.store.url.concat("?act=admin-upload&tp=image")}
              listType="picture-card"
              name="image"
              fileList={this.data.detail}
              onPreview={this.handlePreview}
              onChange={({file,fileList }) => {
                if(file.type && !this._beforeUpload(file)){return;}
                const images=fileList.map((item,index)=>{
                  let data=item;
                  if(item.response){
                    const sfx=item.response.data.split(',');
                    data={
                      uid: `-${index+1}`,
                      name: "image.".concat(sfx[sfx.length-1]),
                      status: 'done',
                      url:item.response.data
                    }
                  }
                  return data;
                });
                this.product.set("data-detail",images);
              }}
              beforeUpload={file=>this._beforeUpload(file)}
              >
              {this.data.detail.length >= 20 ? null : uploadButton}
            </Upload>
          </TabPane>
          <TabPane style={tabSty} tab="类型参数" key="args">
            <View style={{flexDirection:"column",jusitifyContent:"space-between"}}>
              <View style={{flexDirection:"column"}}>
                {
                  this.data.product.args.map((item,index)=>(
                    <View key={index} style={sty.view}>
                      <Input
                        style={{marginRight:"5px"}}
                        size="large"
                        addonBefore="参数名"
                        disabled={this.loading}
                        placeholder="参数名称"
                        value={item.k}
                        onChange={e=>this.product.set("data-product-args-".concat(index,"-k"),e.target.value)}
                      />
                      <Input
                        style={{marginRight:"5px"}}
                        size="large"
                        addonBefore="参数值"
                        disabled={this.loading}
                        placeholder="参数值数据"
                        value={item.v}
                        onChange={e=>this.product.set("data-product-args-".concat(index,"-v"),e.target.value)}
                      />
                      <Button 
                        type="link"
                        icon={<CloseOutlined />}
                        danger
                        onClick={()=>{
                          console.log("index",index)
                          const args = this.data.args;
                          args.splice(index,1);
                          console.log(args);
                          this.product.set("data-product-args",args);
                        }}
                        />
                    </View>
                  ))
                }
              </View>
              <View style={{padding:"10px 0"}}>
                <Button
                  onClick={()=>{
                    const args=this.data.product.args;
                    args.push({k:"",v:""});
                    this.product.set("data-product-args",args);
                    console.log(args);
                  }}
                >
                  增加一项
                </Button>
              </View>
            </View>
          </TabPane>
          <TabPane style={tabSty} tab="套餐价格" key="prices">
            <View style={{flexDirection:"column",jusitifyContent:"space-between"}}>
              <View style={{flexDirection:"column"}}>
                {
                  this.data.product.prices.map((item,index)=>(
                    <View key={index} style={sty.view}>
                      <Input
                        style={{marginRight:"5px"}}
                        size="large"
                        addonBefore="型号颜色"
                        disabled={this.loading}
                        placeholder="参数名称"
                        value={item.tit}
                        onChange={e=>this.product.set("data-product-prices-".concat(index,"-tit"),e.target.value)}
                      />
                      <Input
                        style={{marginRight:"5px"}}
                        size="large"
                        addonBefore="库存"
                        disabled={this.loading}
                        placeholder="库存"
                        value={item.inventory}
                        onChange={e=>{
                          let v = e.target.value;
                          if(!/^\d+$/.test(v) && v!==""){
                            v="";
                          }else if(v>999999){
                            v=999999;
                          }
                          this.product.set(
                            "data-product-prices-".concat(index,"-inventory"),
                            v
                          )
                        }}
                      />
                      <Input
                        style={{marginRight:"5px"}}
                        size="large"
                        addonBefore="价格"
                        disabled={this.loading}
                        placeholder="价格"
                        value={item.price}
                        onChange={e=>{
                          const v = e.target.value;
                          let value= /^\d{1,9}(\.\d{0,2})?/.test(v)?v.match(/^\d{1,9}(\.\d{0,2})?/g)[0]:"";
                          if(value>1000000){value=999999.99}
                          this.product.set(
                            "data-product-prices-".concat(index,"-price"),
                            value
                          )
                        }}
                      />
                      <Button
                        type="link"
                        icon={<CloseOutlined />}
                        danger
                        onClick={()=>{
                          console.log("index",index)
                          const prices = this.data.product.prices;
                          prices.splice(index,1);
                          console.log(prices);
                          this.product.set("data-product-prices",prices);
                        }}
                        />
                    </View>
                  ))
                }
              </View>
              <View style={{padding:"10px 0"}}>
                <Button
                  onClick={()=>{
                    const prices=this.data.product.prices;
                    prices.push({tit:"",inventory:"",price:"",});
                    this.product.set("data-product-prices",prices);
                  }}
                >
                  增加一项
                </Button>
              </View>
            </View>
          </TabPane>
          <TabPane style={tabSty} tab="固定租期" key="leaseTerm">
            <View style={{flexDirection:"column",jusitifyContent:"space-between"}}>
              <View style={{flexDirection:"column"}}>
                {
                  this.data.product.leaseTerm.map((item,index)=>(
                    <View key={index} style={sty.view}>
                      <Input
                        size="large"
                        addonBefore="租期天数"
                        addonAfter="天"
                        disabled={this.loading}
                        placeholder="租期天数"
                        value={item}
                        // onChange={e=>this.product.set("data-prices-".concat(index,"-v"),e.target.value)}
                        onChange={e=>{
                          const v = e.target.value;
                          let value= /^\d{1,9}(\.\d{0,2})?/.test(v)?v.match(/^\d{1,9}(\.\d{0,2})?/g)[0]:"";
                          if(value>10000000){value=9999999.99}
                          this.product.set(
                            "data-product-leaseTerm-".concat(index),
                            e.target.value
                          )
                        }}
                      />
                      <Button
                        type="link"
                        icon={<CloseOutlined />}
                        danger
                        onClick={()=>{
                          console.log("index",index)
                          const leaseTerm = this.data.product.leaseTerm;
                          leaseTerm.splice(index,1);
                          console.log(leaseTerm);
                          this.product.set("data-product-leaseTerm",leaseTerm);
                        }}
                        />
                    </View>
                  ))
                }
              </View>
              <View style={{padding:"10px 0"}}>
                <Button
                  onClick={()=>{
                    const leaseTerm=this.data.product.leaseTerm;
                    leaseTerm.push(0);
                    this.product.set("data-product-leaseTerm",leaseTerm);
                  }}
                >
                  增加一项
                </Button>
              </View>
            </View>
          </TabPane>
        </Tabs>
      </View>
    );
  }
}

export default ProductEdit;